﻿using Finance.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Finance.Web.Controllers
{
    public class BankController : Controller
    {
         [Authorize]
        public ActionResult Index()
        {
            return PartialView(); 
        }

         [Authorize]
        public ActionResult Create()
        {
            return PartialView();
        }

         [Authorize]
        public ActionResult Query(string name, int offset, int count)
        {
            using (FinanceContext context = new FinanceContext())
            { 
                IEnumerable<Bank> banks = context.Banks.OrderBy(i => i.Name);
                if (name != null && name != string.Empty)
                    banks = banks.Where(i => i.Name.IndexOf(name, StringComparison.InvariantCultureIgnoreCase) != -1);

                banks = banks.Skip(offset).Take(count);

                return Json(banks.Select( b => new BankViewModel(b)).ToList());
            }
        }


         [Authorize]
        public ActionResult Save(Bank bank)
        {
            if (ModelState.IsValid)
            {
                using (FinanceContext context = new FinanceContext())
                {
                    if (bank.Code != 0)
                    {
                        var exist = context.Banks.FirstOrDefault(i => i.Code == bank.Code);
                        if (exist == null)
                            return HttpNotFound();
                        else
                        {
                            exist.Name = bank.Name;
                            exist.Info = bank.Info;
                            context.SaveChanges();
                            return new JsonResult();
                        }
                    }
                    else
                    {

                        var exist = context.Banks.FirstOrDefault(i => i.Name == bank.Name);
                        if (exist != null)
                            ModelState.AddModelError("Name", "Уже существует такой банк");
                        else
                        {
                            context.Banks.Add(bank);
                            context.SaveChanges();
                            return new JsonResult();
                        }
                    }
                }
            }
            return Finance.Web.Utils.AngularFormErrors(this);            
        }
         [Authorize]
        public ActionResult Get(int code)
        {
            using (FinanceContext context = new FinanceContext())
            {
                var bank = context.Banks.FirstOrDefault(i => i.Code == code);
                if (bank != null)
                    return Json(new BankViewModel(bank));
                else
                    return HttpNotFound();
            }
        }
    }
}
